import { Component,OnInit,ChangeDetectorRef } from '@angular/core';
import { appService } from '../../../../my-service/app.service';
import { fadeIn } from '../../../../animate';
import { UtilService } from '../../../../my-service/util.service'
import {canvasmsg} from "../canvasmsg";
import { classService } from '../../../../my-service/class.service'
import { ActivatedRoute ,Params} from '@angular/router';
@Component({
  selector: 'classtotimeline-root',
  templateUrl: './classtotimeline.component.html',
  styleUrls: ['./classtotimeline.component.css'],
  animations: [fadeIn]
})
export class classtotimelineComponent implements OnInit {
  FK_CanvasGuid
  img
  constructor(private appservice: appService,
   public ref: ChangeDetectorRef,
    private activatedRoute: ActivatedRoute, private classService: classService,private utilService: UtilService) {
      this.FK_CanvasGuid=this.utilService.canvas().guid
      this.img=this.utilService.canvas().img
    }
  breadcrumb = {
    name: '主页',
    path: '',
    children: {
      name: ''
    }
  }
  canvasmsg: canvasmsg = {
    BackGroundImg: '',
    Canvaschoose: "每组或每人一张",
    Description: '加载中',
    Developer: "舟道科技",
    ID: 0,
    Imgurl: '',
    Logo: '',
    MainRatio: 0.517,
    Name: '加载中',
    PK_CanvasGuid: '',
    Packetmode: '个人或分组',
    SmallImgurl: '',
    Status: 1,
    Type: '',
    Updatetime: '',
    Usages: '',
    Usagescenario: "任何场景",
    Versions: '1.0',
    EnglishName: ''
  };

  FK_CreatorGuid
  FK_ClassGuid= this.activatedRoute.snapshot.paramMap.get('FK_ClassGuid');;
  trainlist=[]
  load=false;
  timeline=false;
  recoveryshow=false;
  form = {
    Title: '',
    Description: '',
    Password: '00000',
    FK_ClassGuid: '000000',
    class: '匿名模式',
    PK_TrainningGuid:''
  }
  addwindow=false;
  editwindow=false;
  selectbox = false;
  classlist = [];
  usermsg = {
    Answer: '',
    Cover: '',
    Description: '',
    Email: '',
    FK_OccupationGuid: '',
    FK_ProblemGuid: '',
    Idiograph: '',
    Name: '',
    PK_OrgGuid: '',
    PK_UserGuid: '',
    Phone: '',
    Sex: '',
    UserName: '',
    content: '',
    occupation: '',
    orgName: ''
  };

  ngOnInit() {
    this.utilService.getUserInfo().then(re=>{
          this.FK_CreatorGuid=re.userGuid
          this.form.Password = this.getCode(5)
          this.activatedRoute.params.subscribe((params: Params) => {
            this.breadcrumb.children.name=params.ClassName
          })
          this.appservice.lpplist({
            FK_CanvasGuid:this.FK_CanvasGuid,
            FK_CreatorGuid:this.FK_CreatorGuid,
            FK_ClassGuid:this.FK_ClassGuid,
            Status:1
          }).then((re2)=>{
            this.trainlist=re2;
          }).then(()=>{
            this.load=true;
          })

          this.appservice.getcanvas(this.FK_CanvasGuid).then(re => {
            this.canvasmsg = re
            this.form.Title = `${this.canvasmsg.Name}${this.getDate()}`
          })
          this.appservice.getThisUser(this.FK_CreatorGuid).then(re => {
            if (re.status) {
              this.usermsg = re.data;
              this.form.Description = re.data.UserName + '创建的训练'
            }
          })
          this.classService.ClassForUser(this.FK_CreatorGuid).then(re => {
            let data = [];
            data.push(
              {
                ClassName: '匿名模式',
                PK_ClassGuid: ''
              }
            )
            for (let i = 0; i < re.data.length; i++) {
              if(re.data[i].PK_ClassGuid==this.FK_ClassGuid){
                this.form.class=re.data[i].ClassName;
                this.form.FK_ClassGuid=re.data[i].PK_ClassGuid;
              }
                data.push(re.data[i])
            }
            this.classlist = data
          })
        })
    // this.breadcrumb.path=`/home/list/${this.FK_CanvasGuid}`
   }
   change($event){
    this.timeline=!this.timeline
   }
   del($event){
    this.appservice.lpplist({
      FK_CanvasGuid: this.FK_CanvasGuid,
      FK_CreatorGuid: this.FK_CreatorGuid,
      FK_ClassGuid:this.FK_ClassGuid,
      Status: 1
    }).then((re2) => {
      this.trainlist = re2;
    })
    this.recoveryshow=false;
  }
  editform(item){
    let _class='匿名模式';
    this.classlist.forEach(el => {
      if(el.PK_ClassGuid==item.FK_ClassGuid){
        _class=el.ClassName
      }
    });
    this.form={
      Title: item.Title,
      Description: item.Description,
      Password: item.Password,
      FK_ClassGuid:item.FK_ClassGuid,
      class:_class,
      PK_TrainningGuid:item.PK_TrainningGuid
    }
    this.editwindow=true;
    }
   addform() {
        if (this.form.Title == '') {
          this.utilService.remind('error', '名字不能为空!')
          return
        }
        if (this.form.Password == '') {
          this.utilService.remind('error', '邀请码不能为空!')
          return
        }
        if (this.form.Password.length != 5) {
          this.utilService.remind('error', '请输入五位邀请码!')
          return
        }
        let data = {
          FK_CanvasGuid:'',
          Title: '',
          Description: '',
          CreaterGuid: '',
          CreaterName: '',
          CreaterOrgName:'',
          Password: '',
          FK_ClassGuid: ''
        }

          data={
            FK_CanvasGuid:this.FK_CanvasGuid,
            Title:this.form.Title,
            Description:this.form.Description,
            CreaterGuid:this.FK_CreatorGuid,
            CreaterName:this.usermsg.UserName,
            CreaterOrgName:this.usermsg.orgName,
            Password:this.form.Password,
            FK_ClassGuid:this.form.FK_ClassGuid
          }
          this.appservice.postcanvastrain(data).then(re => {
            if (re.status == 1) {
              this.addwindow = false;
              this.initialize();
              let apiConfig={
                projectName:this.utilService.canvas().projectName,
                guid:re.PK_TrainningGuid,
                endTime: this.utilService.timestamp(new Date())+2592000,
                FK_ClassGuid:data.FK_ClassGuid.length>10?data.FK_ClassGuid:null,
                FK_UserGuid:this.FK_CreatorGuid
              }
              this.utilService.createCode(apiConfig).then(rec=>{
                this.appservice.bindCode(re.PK_TrainningGuid,rec.code).then((re6)=>{
                  this.appservice.lpplist({
                    FK_CanvasGuid: this.FK_CanvasGuid,
                    FK_CreatorGuid: this.FK_CreatorGuid,
                    Status: 1
                  }).then((re2) => {
                    this.trainlist = re2;
                  })
                })
              })
            }
            else { this.utilService.remind('error', '创建失败，请刷新，稍后重试！') }
          })
      }
      initialize(){
        this.form={
          Title: `${this.canvasmsg.Name}${this.getDate()}`,
          Description:   this.usermsg.UserName + '创建的训练',
          Password:  this.getCode(5),
          FK_ClassGuid: '000000',
          class: '匿名模式',
          PK_TrainningGuid:''
        }
      }
      getDate() {
        let date = new Date(); //取当前时间
        let month = date.getMonth() + 1;
        let months, strDates;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
          months = "0" + month;
        }else{
          months=`${month}`
        }
        if (strDate >= 0 && strDate <= 9) {
          strDates = "0" + strDate;
        } else {
          strDates = strDate
        }
        let currentdate = date.getFullYear() + months + strDates;
        return currentdate;
      }
  getCode(num) {
    let id = "";
    for (let i = 1; i <= num; i++) {
      let n = Math.floor(Math.random() * 10.0).toString(10);
      id += n;

    }
    return id;
  }
  shuiji() {
    this.form.Password = this.getCode(5);
  }
  select(item) {
    this.form.FK_ClassGuid = item.PK_ClassGuid;
    this.form.class = item.ClassName;
    this.selectbox = false;
  }
  checknum(num, item) {
    if (item == 'Password') {
      if (JSON.stringify(this.form[item]).length > num) {
        this.form[item] = parseInt(JSON.stringify(this.form[item]).slice(0, num))
      }
    } else {
      if (this.form[item].length > num) {
        this.form[item] = this.form[item].slice(0, num)
      }
    }
  }
  edit(){
    this.utilService.comfirm('确定要修改该训练吗？',()=>{
          if (this.form.Title == '') {
            this.utilService.remind('error', '名字不能为空!')
            return
          }
          if (this.form.Password == '') {
            this.utilService.remind('error', '邀请码不能为空!')
            return
          }
          if (this.form.Password.length != 5) {
            this.utilService.remind('error', '请输入五位邀请码!')
            return
          }
          let data = {}
            data={
              Title:this.form.Title,
              Description:this.form.Description,
              Password:this.form.Password,
              FK_ClassGuid:this.form.FK_ClassGuid,
              PK_TrainningGuid:this.form.PK_TrainningGuid
            }
          this.appservice.edittrain(data).then(re=>{
            if(re.status==1){
              this.editwindow=false;
              this.initialize();
              this.appservice.lpplist({
                FK_CanvasGuid: this.FK_CanvasGuid,
                FK_CreatorGuid: this.FK_CreatorGuid,
                FK_ClassGuid:this.FK_ClassGuid,
                Status: 1
              }).then((re2) => {
                this.trainlist = re2;
              })
            }else{
             this.utilService.remind('error','创建失败，请刷新，稍后重试！')
            }
          })
    })
  }
}
